require.config({baseUrl: '/js/lib',urlArgs: "v0.0.3"});
require(['zepto', 'lib'], function($, lib) {
  var fn = {}, lib = new lib();
  $.extend(fn, {
    isEditing: false,
    totalPrice: 0,
    init: function(){
      var _t = this;
      _t.initCart();
      _t.bindEvent();
      lib.getCartNum();
    },
    bindEvent: function(){
      var _t = this;
      /*编辑完成*/
      $(document).on("tap", "nav > i", function(){
        $(".ui-order-t").remove();
        if($(this).text() === "编辑"){
          _t.isEditing = true;
          $(this).text("完成");
          $(".ui-cart-select").addClass('ui-no-choose').removeClass('ui-choose');
          $("body").append('<div class="ui-order-t ui-cart-op ui-input-foucs-hide"> <div> <i class="ui-no-choose ui-cart-select" style="margin: 0;margin-top:0.5rem;float: left;"></i>全选 </div> <div class="ui-red-botton" style="width:4.4rem">删除</div> </div>');
        }else{
          _t.isEditing = false;
          $(this).text("编辑");
          $("body").append('<div class="ui-order-t ui-input-foucs-hide"> <div> <i class="ui-no-choose ui-cart-select" style="margin: 0;margin-top:0.5rem;float: left;"></i>全选 </div> <div>总金额：<i>￥'+ _t.totalPrice.toFixed(2) +'</i></div> <div class="ui-red-botton" style="width:4.4rem">去结算</div> </div>');
          _t.initCart();
        }
      });
      
      /*对商品数量操作*/
      $(document).on("tap", ".ui-g-num i", function(e){
        if(_t.isEditing) return;
        var num = Number($(this).parent().children('input').val());
        if($(this).attr('class') === 'ui-plus'){
          if(num > 1) num--;
          else return;
        }else{
          if(num < 99) num++;
          else return;
        }
        $(this).parent().children('input').val(num);
        _t.changeGoodNum($(this).parents('.ui-goods-info').attr('data-cartId'), num);
      });
      
      /*输入框失焦点*/
      $(document).on("blur", ".ui-g-num input", function(e){
        if(_t.isEditing) return;
        lib.onLoading();
        var num = Number($(this).parent().children('input').val());
        if(isNaN(num)){
          num = 1
        }else{
          if(num > 99){
            num = 99;
          }else if(num < 1){
            num = 1;
          }
        }
        $(this).parent().children('input').val(num);
        _t.changeGoodNum($(this).parents('.ui-goods-info').attr('data-cartId'), num);
      });
      
      /*点击跳转详情*/
      $(document).on("tap", ".ui-goods-info", function(e){
        obj = event.srcElement ? event.srcElement : event.target;
        if(_t.isEditing && obj.className.indexOf('ui-cart-select') === -1){
          $(this).children().children('i').attr('class') === 'ui-no-choose ui-cart-select' ? 
          $(this).children().children('i').attr('class', 'ui-choose ui-cart-select') :
          $(this).children().children('i').attr('class', 'ui-no-choose ui-cart-select');
          var isShopAll = true;
          $.each($(this).parents('.ui-per-shop').children('.ui-goods-info'), function(k, v) {
            if($(v).children().children('i').attr('class') === 'ui-no-choose ui-cart-select'){
              isShopAll = false;
            }
          });
          isShopAll ? $(this).parents('.ui-per-shop').children('.ui-shop-name').children('.ui-cart-select').attr('class', 'ui-choose ui-cart-select') : $(this).parents('.ui-per-shop').children('.ui-shop-name').children('.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
          var isAll = true
          $.each($('.ui-per-shop > .ui-shop-name > i.ui-cart-select'), function(k, v) {
            if($(v).attr('class') === 'ui-no-choose ui-cart-select'){
              isAll = false;
            }
          });
          isAll ? $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-choose ui-cart-select') : $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
        }else{
          if(['I', 'INPUT'].indexOf(obj.tagName) === -1){
            location.href = "/detail.html";
          }
        }
      });
      
      /*商品选择*/
      $(document).on('tap', ".ui-goods-info > li > i", function(){
        var cartIds = [], opt = 0;
        $(this).attr('class') === 'ui-no-choose ui-cart-select' ? 
          $(this).attr('class', 'ui-choose ui-cart-select') :
          $(this).attr('class', 'ui-no-choose ui-cart-select');
        
        var isShopAll = true;
        $.each($(this).parents('.ui-per-shop').children('.ui-goods-info'), function(k, v) {
        	if($(v).children().children('i').attr('class') === 'ui-no-choose ui-cart-select'){
        	  isShopAll = false;
        	}
        });
        isShopAll ? $(this).parents('.ui-per-shop').children('.ui-shop-name').children('.ui-cart-select').attr('class', 'ui-choose ui-cart-select') : $(this).parents('.ui-per-shop').children('.ui-shop-name').children('.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
        var isAll = true
        $.each($('.ui-per-shop > .ui-shop-name > i.ui-cart-select'), function(k, v) {
          if($(v).attr('class') === 'ui-no-choose ui-cart-select'){
            isAll = false;
          }
        });
        isAll ? $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-choose ui-cart-select') : $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
        _t.selectOrCancel([$(this).parents('.ui-goods-info').attr('data-cartId')], ($(this).attr('class') === 'ui-no-choose ui-cart-select' ? 0 : 1));
      });
      
      /*商铺选择*/
      $(document).on('tap', ".ui-shop-name  > i.ui-cart-select", function(){
        var cartIds = [], opt = 0;
        if($(this).attr('class') === 'ui-no-choose ui-cart-select'){
          $(this).attr('class', 'ui-choose ui-cart-select');
          $(this).parents('.ui-per-shop').find('.ui-cart-select').attr('class', 'ui-choose ui-cart-select');
           opt = 1;
        }else{
          $(this).attr('class', 'ui-no-choose ui-cart-select');
          $(this).parents('.ui-per-shop').find('.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
        }
        
        var isAll = true
        $.each($('.ui-per-shop > .ui-shop-name > i.ui-cart-select'), function(k, v) {
          if($(v).attr('class') === 'ui-no-choose ui-cart-select'){
            isAll = false;
          }
        });
        isAll ? $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-choose ui-cart-select') : $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
        
        $.each($(this).parents('.ui-per-shop').find('.ui-goods-info'), function(k, v) {
          cartIds.push($(v).attr('data-cartId'));
        });
        _t.selectOrCancel(cartIds, opt)
        
      });
      
      /*购物车全选*/
      $(document).on('tap', ".ui-order-t i.ui-cart-select", function(){
        var cartIds = [], opt = 0;
        if($(this).attr('class') === 'ui-no-choose ui-cart-select'){
          $('.ui-cart-select').attr('class', 'ui-choose ui-cart-select');
          opt = 1;
        }else{
          $('.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
        }
        $.each($('.ui-goods-info'), function(k, v) {
        	cartIds.push($(v).attr('data-cartId'));
        });
        _t.selectOrCancel(cartIds, opt);
      });
      
      /*删除操作*/
      $(document).on('tap', ".ui-order-t.ui-cart-op .ui-red-botton", function(){
        var cartIds = [];
        $.each($(".ui-choose").parents('.ui-goods-info'), function(k, v) {
        	cartIds.push($(v).attr('data-cartId'));
        });
        if(cartIds.length === 0){
          lib.showMessage('请选择要删除的商品');
          return;
        }
        lib.onLoading();
        lib.ajx(lib.getReq().ser + '/shoppingCart/clearByCartIds.action', {cartIds: cartIds}, function(data){
          lib.showMessage(data.info);
          _t.initCart();
          lib.getCartNum();
        }, function(){
          lib.showMessage('网络错误,请稍后再试');
        })
      });
      
      /*结算操作*/
      $(document).on('tap', ".ui-order-t:not(.ui-cart-op) .ui-red-botton", function(){
        var cartIds = [];
        $.each($(".ui-choose").parents('.ui-goods-info'), function(k, v) {
          cartIds.push($(v).attr('data-cartId'));
        });
        if(cartIds.length === 0){
          lib.showMessage('请选择要结算的商品');
          return;
        }
        lib.onLoading();
        lib.ajx(lib.getReq().ser + '/order/orderConfirmInfo.action', {makeType: 1}, function(data){
          if(data.infocode === "0"){
            sessionStorage.orderConfirmInfo = JSON.stringify(data.info);
            location.href = "/order/confirm_order.html";
            return;
          }else if(data.infocode === "2"){
            location.href = "/login.html?backUrl=" + lib.getBackUrl();
            return;
          }
          lib.showMessage(data.info);
        }, function(){
          lib.showMessage('网络错误,请稍后再试');
        })
      });
    },
    selectOrCancel: function(cartIds, opt){
      var _t = this;
      if(_t.isEditing) return;
      lib.onLoading();
      lib.ajx(lib.getReq().ser +　'shoppingCart/selectOrCancel.action', {cartIds: cartIds, opt: opt}, function(data){
        if(data.infocode !== "0"){
          lib.showMessage(data.info);
        }
        _t.initCart();
      }, function(){
        lib.showMessage('网络错误,请稍后再试');
      });
    },
    changeGoodNum: function(goodsId, goodsNum){
      var _t = this;
      if(_t.isEditing) return;
      lib.ajx(lib.getReq().ser +　'shoppingCart/updateGoodsNum.action', {cartId: goodsId, goodsNum: goodsNum}, function(data){
        lib.getCartNum();
        if(data.infocode !== "0"){
          lib.showMessage(data.info);
        }
        _t.initCart();
      }, function(){
        lib.showMessage('网络错误,请稍后再试');
      });
    },
    initCart: function(){
      var _t = this;
      lib.onLoading();
      lib.ajx(lib.getReq().ser +　'shoppingCart/cartList.action', {}, function(data){
        if(data.infocode === "0"){
          if(data.info.length === 0){
            $(".ui-nav i").remove();
            $(".ui-all-goods, .ui-order-t").hide();
            $("body").append('<dl class="ui-cart-empty"><dt style="width: 4.14rem;margin: 0 auto;margin-bottom: 1.6rem;margin-top: 2rem;"><img src="/images/cart_empty.png"></dt><dd style="text-align: center;font-size: 0.64rem;"><a href="/" style="color: #999;">购物车空空如也~快去购物吧!</a></dd></dl>')
            $("body").css("background-color", "white");
          }else{
            let h = '', isAll = true;
            _t.totalPrice = 0;
            $.each(data.info, function(K, V) {
              let shopIsChoose = true, ul = '';
              $.each(V.goodsList, function(k, v) {
                if(!v.isOpt){
                  shopIsChoose = false;
                  isAll = false;
                }else{
                  _t.totalPrice += Number(v.goodsNum) * Number(v.sellPrice);
                }
                ul += `<ul class="ui-goods-info" data-goodsId="${v.goodsId}" data-cartId="${v.shoppingCartId}">
                        <li>
                          <i class="${v.isOpt && !_t.isEditing ? 'ui-choose' : 'ui-no-choose'} ui-cart-select"></i>
                          <div class="ui-g-img"><img src="${lib.getReq().imgPath + v.mainPictureJpg}" /></div>
                          <ul class="ui-g-desc">
                            <li>${v.chName}</li>
                            <li>
                              <i class="ui-g-price">￥${v.sellPrice}</i>
                              <div class="ui-g-num">
                                <i class="ui-plus"></i>
                                <input value="${v.goodsNum}" type="tel">
                                <i class="ui-add"></i>
                              </div>
                            </li>
                          </ul>
                        </li>
                      </ul>`
              });
              h +=  `<div class="ui-per-shop" data-storageId="${V.storageId}">
                      <div class="ui-shop-name">
                        <i class="${shopIsChoose && !_t.isEditing ? 'ui-choose' : 'ui-no-choose'} ui-cart-select"></i>
                        <i>${V.storageName}</i>
                        <i class="ui-r-b" style="margin-top: 0.62rem;margin-left: 5px"></i>
                        <i>${V.goodsList[0].cartDate}</i>
                      </div>
                      ${ul}
                    </div>`;
            });
            
            $(".ui-all-goods").html(h);
            $(".ui-totalPrice").html('总金额：<i>￥'+ _t.totalPrice.toFixed(2) +'</i>');
            isAll && !_t.isEditing ? $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-choose ui-cart-select') : $('.ui-order-t  i.ui-cart-select').attr('class', 'ui-no-choose ui-cart-select');
          }
        }else{
          lib.showMessage(data.info);
        }
      }, function(){
        lib.showMessage('网络错误,请稍后再试');
      });
    }
  });
  
  fn.init();
});